<template>
  <van-popup v-model="show" position="bottom">
    <van-cascader
      v-model="cascaderValue"
      title=""
      :options="places"
      @close="toClose"
      @change="onChange"
      @finish="onFinish"
    />
  </van-popup>
</template>

<script>
import { getAreaList } from '@/api/base'

export default {
  name: 'selectAddress',
  data() {
    return {
      show: true
    }
  },
  created() {},
  methods: {
    toClose() {},
    // 检测区划改变
    async onChange({ value, selectedOptions, tabIndex }) {
      if (this.origin === '进口' || tabIndex > 2) return
      // console.log(value, selectedOptions, tabIndex)
      const { code, data } = await getAreaList({
        parentAreaCode: value
      })
      let placeIndex = ''
      let target = {}

      if (tabIndex > 0) {
        for (let i = 0; i <= tabIndex; i++) {
          if (selectedOptions[i].parentIndex !== undefined) {
            let parentIndex = selectedOptions[i].parentIndex
            console.log('parentIndex:', parentIndex)
            target = this.places[parentIndex].children
          }
        }
        placeIndex = target.findIndex((item) => item.value === value)
        target = target[placeIndex]
      } else {
        placeIndex = this.places.findIndex((item) => item.value === value)
        target = this.places[placeIndex]
      }

      if (code === '0') {
        data.forEach((item) => {
          if (tabIndex < 1) {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              children: [],
              parentIndex: placeIndex
            })
          } else {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              parentIndex: placeIndex
            })
          }
        })
      }
    },
    // 区划完成
    onFinish({ selectedOptions }) {
      this.supplyInfo.areaName =
        selectedOptions.map((option) => option.text).join('') || ''
      // 获取区划码
      this.supplyInfo.originPlaceInfoName =
        selectedOptions[selectedOptions.length - 1].value
      console.log('finish')
      this.show = false
    }
  }
}
</script>
